/**
 * umiRequest 网络请求工具
 * 更详细的 api 文档: https://github.com/umijs/umi-request
 */
import {Context, extend} from 'umi-request';
import {codeMessage, param} from "./umi-request.config";
import {message, notification} from 'antd';
import {antd2Mp, mp2Antd, antd2Jpa, jpa2Antd} from "./antd-page.util";
/**
 * 异常处理程序
 */
const errorHandler = (error: { response: Response }): Response => {
  const { response } = error;
  if (response && response.status) {
    // @ts-ignore
      const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;

    notification.error({
      message: `请求错误 ${status}: ${url}`,
      description: errorText,
    });
  } else if (!response) {
    notification.error({
      description: '您的网络发生异常，无法连接服务器',
      message: '网络异常',
    });
  }
  return response;
};

/**
 * 配置request请求时的默认参数
 */
const defaultRequestParams = {
    errorHandler, // 默认错误处理
    credentials: 'include', // 默认请求是否带上cookie
    requestType: "form",
    prefix:'api',
    headers:{
        [param.client_name]:param.client_key,
    }
};
// @ts-ignore
const umiRequest = extend(defaultRequestParams);

 function setHeaderToken(url:string,options:any):any{
    if( url === param.refresh_url || url === `${options.prefix}${param.refresh_url}`){
        return {url,options};
    }
    // TODO 请求头设置
    // const tokenInfo = getAuthority();
    // if(!tokenInfo){
    //     window.location.href = param.login_url;
    //     cleanAuthority();
    //     return null;
    // }
    //
    // let {headers} = options;
    // headers = {...headers, [param.token_name]: `${tokenInfo.accessToken}`,};
    // options={...options,headers};
    return {url, options};
}
const interceptor = async (ctx:Context, next:() => void) => {
  let {url,options} = ctx.req;
  let reqBody =setHeaderToken(url,options);
  if(!reqBody){
    return ;
  }
  ctx.req=reqBody;
  await next();
  if(ctx.res.success){
    ctx.res =ctx.res.data ;
  }else{
    console.error(ctx.res.message);
    message.error(ctx.res.message);
  }
}
umiRequest.use(interceptor);

// @ts-ignore
// mybatis plus 分页的封装
const requestMpPage = extend(defaultRequestParams);
requestMpPage.use(async (ctx:Context, next:() => void) => {
    let {url,options} = ctx.req;
    let reqBody =setHeaderToken(url,options);
    if(!reqBody){
        return ;
    }
    let data = reqBody.options.params;
    data = antd2Mp(data);
    reqBody.options.params =data;
    ctx.req=reqBody;
    await next();
    let rdata = ctx.res.data ;
    rdata = mp2Antd(rdata);
    ctx.res = rdata;
});

// @ts-ignore
// jpa 分页的封装
const requestJpaPage = extend(defaultRequestParams);
    requestJpaPage.use(async (ctx:Context, next:() => void) => {
    let {url,options} = ctx.req;
    let reqBody =setHeaderToken(url,options);
    if(!reqBody){
        return ;
    }
    let data = reqBody.options.params;
    data = antd2Jpa(data);
    reqBody.options.params =data;
    ctx.req=reqBody;
    await next();
    const rdata = jpa2Antd(ctx.res.data);
    ctx.res = rdata;
});

function tableRequestError(e:any):Promise<[]>{
    console.info(e);
    message.warn("请求失败");
    return new Promise((resole,reject)=>{
        resole([]);
    });
}
// @ts-ignore
const dataRequest  =  extend({
  ...defaultRequestParams,
  prefix: 'api'
});
// @ts-ignore
const zhjcRequest  = extend({
  ...defaultRequestParams,
  prefix:'data',
});
dataRequest.use(interceptor);
zhjcRequest.use(interceptor);
export  {  tableRequestError, umiRequest, dataRequest , zhjcRequest, requestMpPage, requestJpaPage};
